package wen;

import wen.utils.Clock;

import java.net.MalformedURLException;
import java.util.LinkedList;
import java.util.Queue;


public class Downloader implements Runnable {
    private final String fileLocation;
    Queue<Task> taskQueue;
    private final String suffix;


    public Downloader(String fileLocation, String suffix) {
        this.fileLocation = fileLocation;
        this.suffix = suffix;
        taskQueue = new LinkedList<>();
        System.out.println("[DOWNLOADER] Downloader created.");
    }


    public void addATask(String urlString, String fileName) {
        Task task = null;
        try {
            task = new Task(urlString, fileName + suffix, fileLocation);
        } catch (MalformedURLException e) {
            System.out.println("[DOWNLOADER ERROR] Failed to add task.");
        }
        taskQueue.add(task);
        System.out.println("[DOWNLOADER] Download task " + fileName + " added.");
    }

    @Override
    public void run() {
        int queueSize = taskQueue.size();
        Clock clock = new Clock();
        while (!taskQueue.isEmpty()) {
            taskQueue.poll().run();
        }
        System.out.println("[DOWNLOADER] Downloaded " + queueSize + " files in " + clock.getDuration() + " ms.");
    }

}
